package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 新增分类
     *
     * @param categoryDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCategory(CategoryDTO categoryDTO) {
        Category category = new Category();
        //属性拷贝
        BeanUtils.copyProperties(categoryDTO, category);
        //分类状态默认为禁用状态0
        category.setStatus(StatusConstant.DISABLE);
        //设置创建时间、修改时间、创建人、修改人
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateUser(BaseContext.getCurrentId());
        category.setUpdateUser(BaseContext.getCurrentId());
        /*  categoryMapper.insertCategory(category);*/
        return this.save(category) ? 1 : 0;
    }

    /**
     * 分页查询菜品分类
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult selectCategoryList(CategoryPageQueryDTO dto) {
        IPage<Category> defaltPage = new Page<>(dto.getPage(), dto.getPageSize());
        LambdaQueryWrapper <Category> wrapper = new LambdaQueryWrapper <>();
        if (dto.getName() != null) {
            wrapper.like(Category::getName, dto.getName());
        }
        if (dto.getType() != null) {
            wrapper.eq(Category::getType, dto.getType());
        }
        IPage<Category> pageCategory = categoryMapper.selectPage(defaltPage, wrapper);
        long total = pageCategory.getTotal();
        List records = pageCategory.getRecords();
        PageResult pageResult = new PageResult(total, records);
        return pageResult;
    }
}